import React, { Component } from 'react'
import PubSub from 'pubsub-js';
import axios from 'axios';

export default class LOLMain extends Component {

    state = {
        heros: [],
        is_first: true, //是否为首次进入
        is_sending: false, //是否正在发送请求
    }

    render() {
        return (
            <div className="hero-list">
                {
                    this.state.heros.map(item => {
                        return <div key={item.id} className="hero-item">
                                    <img width="100%" src={item.avatar} alt="" />
                                    <p style={{fontSize: '12px'}}>{item.name}</p>
                                </div>
                    })
                }
                {
                    !this.state.is_sending && !this.state.is_first &&  this.state.heros.length === 0  && <div className="empty">暂无数据</div>
                }

                {
                    this.state.is_first && <div className="welcome">欢迎来到英雄联盟</div>
                }

                {
                    this.state.is_sending && <div>加载中....</div>
                }
                
                
            </div>
        )
    }

    //生命周期钩子
    componentDidMount(){
        PubSub.subscribe('search', async (_, data) => {
            //修改状态, 正在发送...
            this.setState({
                is_sending: true,
                is_first: false, //搜索之后, 把 is_first 状态改为 false
                heros: []
            })
            //根据关键字向服务端发送 AJAX 请求获取数据 
            // http://api.xiaohigh.com:8090/lol?q=拉克丝
            let result = await axios('http://api.xiaohigh.com:8090/lol', {
                //设置查询字符串 q 的参数
                params: {
                    q: data
                }
            });

            //修改状态
            this.setState({
                heros: result.data,
                is_sending: false, //发送完毕之后, 修改状态为 false
            })
        });
    }
}

